package httpMiddleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go_gateway/dao"
	"go_gateway/middleware"
	"go_gateway/public"
	"log"
	"strings"
)

// HTTPStripUriMiddleware
// @Description: 清除代理转发时的匹配前缀
// @return gin.HandlerFunc
//
func HTTPStripUriMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1.获取服务信息
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("service not found"))
			c.Abort()
			return
		}
		serviceDetail := serviceInterface.(*dao.ServiceDetail)

		log.Println("before strip uri: ", c.Request.URL.Path)
		// 2.匹配该服务是否启用了前缀匹配模式,且开启了stripUri
		if serviceDetail.HTTPRule.RuleType == public.HTTPRuleTypePrefixURL &&
			serviceDetail.HTTPRule.NeedStripUri == 1 {
			// 空字符串替换前缀匹配,且只替换一次
			c.Request.URL.Path = strings.Replace(c.Request.URL.Path, serviceDetail.HTTPRule.Rule, "", 1)
		}
		log.Println("after strip uri: ", c.Request.URL.Path)
		c.Next()
	}
}
